const mongoose = require('mongoose');
//导入joi模块
const Joi = require('joi');
//创建用户集合规则
const userSchema = new mongoose.Schema({
	username:{
		type: String,
		required: true,
		minlength: 2,
		maxlength: 20
	},
	email: {
		type: String,
		required: true,
		//字段唯一不重复
		unique: true,
	},
	password: {
		type: String,
		required: true,
	},
	role: {
		//admin：超级管理员
		//normal: 普通用户
		type: String,
		required: true
	},
	state: {
		//默认为0，启用状态
		type: Number,
		default: 0
	}
});

//创建用户集合
const User = mongoose.model('User', userSchema);

async function userCreate() {
	const salt = await bcrypt.genSalt(10);
	const pass = await bcrypt.hash('123456', salt);
	const user = await User.create({
	    username: 'mary',
	    email: 'mary@163.com',
	    password: pass,
	    role: 'admin',
	    state: 0
    })    
}
// userCreate();

const validateUser = user => {
	//定义对象验证规则
	const schema = {
		username: Joi.string().min(2).max(12).required().error(new Error('用户名格式错误')),
		email: Joi.string().email().required().error(new Error('邮箱格式错误')),
		password: Joi.string().regex(/^[a-zA-Z0-9]{6,18}$/).required().error(new Error('密码格式错误')),
		role: Joi.string().valid('normal', 'admin').required().error(new Error('角色值无效')),
		state: Joi.number().valid(0, 1).required().error(new Error('状态值无效'))
	}

	return Joi.validate(user, schema);
}
//将用户集合作为模块成员进行导出
module.exports = {
	User,
	validateUser
}